 <?
	class WeixinApi
	{
		public $appid = APPID;
		public $appsecret = APPSECRET;
		public $access_token;
		//public $userInfo;
		
		//构造函数，获取Access Token
		public function init($appid = NULL, $appsecret = NULL)
		{
			/*$this->
			*/
			if($appid && $appsecret){
				$this->appid = $appid;
				$this->appsecret = $appsecret;
			}
			try{
				$mem = new Memcached();
				$mem->addServer('127.0.0.1', 11211);
				$this->access_token = $mem->get('access_token');
				if (empty($this->access_token)){
					$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appid."&secret=".$this->appsecret;
					$res = $this->http_request($url);
					$result = json_decode($res, true);
					$this->access_token = $result["access_token"];
					$mem->set('access_token', $this->access_token,7200);
				}
			}catch(Exception $e){
					$myfile = fopen("/var/www/html/log.txt", "w") or die("Unable to open file!");
					fwrite($myfile, $this->access_token);
					fclose($myfile);
			}
		}

        /**
         * 获取AccessToken
         */
        public  function  getAccessToken(){
            try{
                $mem = new Memcached();
                $mem->addServer('127.0.0.1', 11211);
                $this->access_token = $mem->get('access_token');
                if (empty($this->access_token)){
                    $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".APPID."&secret=".APPSECRET;
                    $res = $this->http_request($url);
                    $result = json_decode($res, true);
                    $this->access_token = $result["access_token"];
                    $mem->set('access_token', $this->access_token,7200);
                }
            }catch(Exception $e){
                $myfile = fopen("/var/www/html/log.txt", "w") or die("Unable to open file!");
                fwrite($myfile, $this->access_token);
                fclose($myfile);
            }
        }
		/**
		  通过code换取网页授权access_token
		  返回数据格式如下:
		  {
			   "access_token":"ACCESS_TOKEN",
			   "expires_in":7200,
			   "refresh_token":"REFRESH_TOKEN",
			   "openid":"OPENID",
			   "scope":"SCOPE",
			   "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
			}
		*/
		public function getOpenIdByCode(&$code){
			$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$this->appid."&secret=".$this->appsecret."&code=".$code."&grant_type=authorization_code";
			$res = $this->http_request($url);
			$result = json_decode($res, true);
			return $result;
		}

        /**
         * 根据Openid获取用户信息
         * @param $openid
         */
        public function getUserInfoByOpenId(&$openid){
            $this->getAccessToken();
            $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$this->access_token."&openid=".$openid."&lang=zh_CN";
            $res = $this->http_request($url);
            $result = json_decode($res, true);
            return $result;
        }



		//HTTP请求（支持HTTP/HTTPS，支持GET/POST）
		protected function http_request($url, $data = null)
		{
			$curl = curl_init();
			curl_setopt($curl, CURLOPT_URL, $url);
			curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
			curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
			if (!empty($data)){
				curl_setopt($curl, CURLOPT_POST, 1);
				curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
			}
			curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
			$output = curl_exec($curl);
			curl_close($curl);
			return $output;
		}

		public function valid()
		{
			$echoStr = $_GET["echostr"];

			//valid signature , option
			if($this->checkSignature()){
				echo $echoStr;
				exit;
			}
		}

		public function responseMsg()
		{
			//get post data, May be due to the different environments
			$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

			//extract post data
			if (!empty($postStr)){
					
					$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
					$RX_TYPE = trim($postObj->MsgType);

					switch($RX_TYPE)
					{
						case "text":
							$resultStr = $this->handleText($postObj);
							break;
						case "event":
							$resultStr = $this->handleEvent($postObj);
							break;
						default:
							$resultStr = "Unknow msg type: ".$RX_TYPE;
							break;
					}
					echo $resultStr;
			}else {
				echo "";
				exit;
			}
		}

		public function handleText($postObj)
		{
			$fromUsername = $postObj->FromUserName;
			$toUsername = $postObj->ToUserName;
			$keyword = trim($postObj->Content);
			$time = time();
			$textTpl = "<xml>
						<ToUserName><![CDATA[%s]]></ToUserName>
						<FromUserName><![CDATA[%s]]></FromUserName>
						<CreateTime>%s</CreateTime>
						<MsgType><![CDATA[%s]]></MsgType>
						<Content><![CDATA[%s]]></Content>
						<FuncFlag>0</FuncFlag>
						</xml>";             
			if(!empty( $keyword ))
			{
				$msgType = "text";
				$contentStr = "感谢您关注【快蚁】\n";
				if(strstr($keyword,"测试")){
                    $contentStr .= '活动页面<a href="http://mp.weixin.qq.com/s?__biz=MzAwMDE4MjkzNA==&mid=207622679&idx=1&sn=d31bc323e98469a448d3cde274f0e80d#rd">获取免费参与码</a>';
                }else{
					$contentStr .= '点击以下链接,参与本次'."\n\r".'<a href="'.DOMAIN.'ac_index.php">友吃送"福梨"活动</a>';
				}
				$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
				
				
				echo $resultStr;
			}else{
				echo "Input something...";
			}
		}

		public function handleEvent($object)
		{
			$contentStr = "";
			switch ($object->Event)
			{
				case "subscribe":
					$contentStr = '感谢您关注【快蚁】'."\n".'点击以下链接,参与本次'."\n\r".'<a href="https://open.weixin.qq.com/connect/oauth2/authorize?appid='.APPID.'&redirect_uri='.DOMAIN.'register.php&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect">友吃送"福梨"活动</a>';
					break;
				default :
					$contentStr = "Unknow Event: ".$object->Event;
					break;
			}
			$resultStr = $this->responseText($object, $contentStr);
			return $resultStr;
		}
		
		public function responseText($object, $content, $flag=0)
		{
			$textTpl = "<xml>
						<ToUserName><![CDATA[%s]]></ToUserName>
						<FromUserName><![CDATA[%s]]></FromUserName>
						<CreateTime>%s</CreateTime>
						<MsgType><![CDATA[text]]></MsgType>
						<Content><![CDATA[%s]]></Content>
						<FuncFlag>%d</FuncFlag>
						</xml>";
			$resultStr = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content, $flag);
			return $resultStr;
		}

		private function checkSignature()
		{
			$signature = $_GET["signature"];
			$timestamp = $_GET["timestamp"];
			$nonce = $_GET["nonce"];    
					
			$token = TOKEN;
			$tmpArr = array($token, $timestamp, $nonce);
			sort($tmpArr);
			$tmpStr = implode( $tmpArr );
			$tmpStr = sha1( $tmpStr );
			
			if( $tmpStr == $signature ){
				return true;
			}else{
				return false;
			}
		}
	}
	$wechatObj = new WeixinApi();
	$wechatObj->init(APPID,APPSECRET);
?>